package com.cq.hd.app.controller;

import com.cq.hd.common.annotation.LoginUser;
import com.cq.hd.common.entity.AppLoginUser;
import com.cq.hd.common.pagination.Page;
import com.cq.hd.common.response.Result;
import com.cq.hd.common.response.Throw;
import com.cq.hd.common.utils.StringUtils;
import com.cq.hd.product.api.TbSearchRecordApi;
import com.cq.hd.product.api.dto.SearchDto;
import com.cq.hd.product.api.dto.SearchRecordPageDto;
import com.cq.hd.product.api.vo.SearchRecordPageVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

@RestController
@RequestMapping("/searchRecord")
@Api(tags = "历史搜索相关接口")
public class SearchRecordController extends BaseController {

    @Autowired
    private TbSearchRecordApi searchRecordApi;

    @ApiOperation(value = "最近10个历史搜索词")
    @ApiResponse(response = SearchRecordPageVo.class, code = 200, message = "接口返回对象参数")
    @GetMapping("/list")
    public Result<Page<SearchRecordPageVo>> pageSearchRecord(@ApiIgnore @LoginUser AppLoginUser appLoginUser) {
        SearchRecordPageDto searchRecordPageDto = new SearchRecordPageDto();
        searchRecordPageDto.setPageNum(1);
        searchRecordPageDto.setPageSize(10);
        searchRecordPageDto.setUserId(appLoginUser.getUserId());
        return searchRecordApi.pageSearchRecord(searchRecordPageDto);
    }

    @ApiOperation(value = "搜索")
    @PostMapping("/search")
    public Result<Object> search(@RequestBody SearchDto searchDto) {
        AppLoginUser appLoginUser = getAppLoginUser();
        if (appLoginUser != null && appLoginUser.getUserId() != null) {
            searchDto.setUserId(appLoginUser.getUserId());
        }

        String keyword = searchDto.getKeyword();
        if (StringUtils.isBlank(keyword)) {
            Throw.isBusinessException("请输入搜索关键词");
        }

        // 去除空格，换行等
        keyword = keyword.replaceAll(" ", "").replaceAll("[\\t\\n\\r]", "");
        if (StringUtils.isBlank(keyword)) {
            Throw.isBusinessException("请输入搜索关键词");
        }
        searchDto.setKeyword(keyword);

        return searchRecordApi.search(searchDto);
    }

    @ApiOperation(value = "删除历史搜索词")
    @DeleteMapping("/delete")
    public Result<Boolean> deleteSearchRecord(@ApiIgnore @LoginUser AppLoginUser appLoginUser, Long id) {
        if (id == null) {
            id = 0L;
        }
        return searchRecordApi.deleteSearchRecord(appLoginUser.getUserId(), id);
    }

}
